<template>
    <view class="withdraw-container">
        <!-- 加载状态 -->
        <view class="loading-container" v-if="isLoading">
            <u-loading mode="circle" size="36"></u-loading>
            <text class="loading-text">加载中...</text>
        </view>
        
        <view v-else>
            <!-- 账户余额概览卡 -->
            <view class="account-overview">
                <view class="overview-amount">
                    <text class="overview-label">可提现余额</text>
                    <text class="overview-value">￥{{withdrawInfo.wallet || '0.00'}}</text>
                </view>
                <view class="overview-details flex">
                    <view class="overview-item">
                        <text class="item-value">{{withdrawInfo.min_withdrawal_money || '0'}}</text>
                        <text class="item-label">最低提现</text>
                    </view>
                    <view class="overview-divider"></view>
                    <view class="overview-item">
                        <text class="item-value">{{withdrawInfo.max_withdrawal_money || '不限'}}</text>
                        <text class="item-label">最高提现</text>
                    </view>
                    <view class="overview-divider"></view>
                    <view class="overview-item">
                        <text class="item-value">{{withdrawInfo.withdrawal_service_charge || '0'}}%</text>
                        <text class="item-label">手续费率</text>
                    </view>
                </view>
            </view>
            
            <view class="withdraw">
                <!-- 提现账户 -->
                <view class="withdraw-card bank-selection m-t-20">
                    <view class="card-header">
                        <view class="card-title">
                            <u-icon name="account" size="32" color="#409EFF" class="icon-margin"></u-icon>
                            提现账户
                        </view>
                        <view class="management-link" @click="goPage('/bundle/pages/bank_list/bank_list')">
                            <text>管理账户</text>
                            <u-icon name="arrow-right" size="24" color="#909399"></u-icon>
                        </view>
                    </view>
                    
                    <!-- 银行账户显示 -->
                    <view class="bank-selection-content">
                        <view v-if="!bank.id" class="empty-bank-tip" @click="goPage('/bundle/pages/bank_list/bank_list')">
                            <u-icon name="plus-circle" size="48" color="#DCDFE6"></u-icon>
                            <text class="empty-tip-text">请添加提现银行账户</text>
                        </view>
                        <view v-else class="selected-bank" @click="goPage('/bundle/pages/bank_list/bank_list')">
                            <view class="bank-icon">
                                {{bank.name ? bank.name.substring(0,1) : ''}}
                            </view>
                            <view class="bank-info">
                                <text class="bank-name">{{bank.name || ''}}</text>
                                <text class="bank-account">{{bank.branch || ''}} · 尾号{{bank.account && bank.account.length >= 4 ? bank.account.substring(bank.account.length-4) : ''}}</text>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 金额输入区域 -->
                <view class="withdraw-card amount-input-card m-t-20">
                    <view class="card-title">
                        <u-icon name="money" size="32" color="#409EFF" class="icon-margin"></u-icon>
                        提现金额
                    </view>

                    <view class="input-container">
                        <text class="currency-symbol">¥</text>
                        <input 
                            type="digit" 
                            v-model="money" 
                            :placeholder="'最低提现'+ (withdrawInfo.min_withdrawal_money || 0) +'元'"
                        />
                    </view>
                    
                    <view class="flex row-between m-t-30">
                        <view class="balance-info">
                            <u-icon name="wallet" size="28" color="#606266" class="m-r-10"></u-icon>
                            可提现余额 <text class="primary-color">￥{{withdrawInfo.wallet || 0}}</text>
                        </view>
                        <view class="withdraw-all-btn"
                            @click="setMaxAmount">全部提现</view>
                    </view>
                </view>

                <!-- 服务费计算 -->
                <view class="withdraw-card fee-card m-t-20" v-if="money">
                    <view class="fee-title">提现明细</view>
                    <view class="fee-item">
                        <text>提现金额</text>
                        <text>¥{{money}}</text>
                    </view>
                    <view class="fee-item">
                        <text>手续费({{withdrawInfo.withdrawal_service_charge || 0}}%)</text>
                        <text>¥{{calculateFee()}}</text>
                    </view>
                    <view class="fee-divider"></view>
                    <view class="fee-item total">
                        <text>实际到账</text>
                        <text>¥{{calculateActual()}}</text>
                    </view>
                </view>
                
                <!-- Tips Card -->
                <view class="withdraw-card withdraw-tips m-t-20">
                    <view class="tips-title">
                        <u-icon name="info-circle" size="28" color="#606266" class="icon-margin"></u-icon>提示信息
                    </view>

                    <view class="tip-item">
                        <view class="tip-bullet"></view>
                        最低可提现：<text class="primary-color">¥{{withdrawInfo.min_withdrawal_money || 0}}</text>
                    </view>
                    
                    <view class="tip-item">
                        <view class="tip-bullet"></view>
                        最高可提现：<text class="primary-color">¥{{withdrawInfo.max_withdrawal_money || "不限"}}</text>
                    </view>
                    
                    <view class="tip-item">
                        <view class="tip-bullet"></view>
                        手续费率：<text class="primary-color">{{withdrawInfo.withdrawal_service_charge || 0}}%</text>
                    </view>

                    <view class="tip-item">
                        <u-icon name="clock" size="24" color="#909399" class="m-r-10"></u-icon>
                        预计到账时间：<text class="muted">1个工作日</text>
                    </view>
                </view>

                <!-- 确认按钮 -->
                <view class="withdraw-btn-container m-t-20">
                    <view 
                        class="withdraw-btn"
                        :class="[money && bank.id ? 'withdraw-btn-active' : '', isSubmitting ? 'withdraw-btn-disabled' : '']"
                        @click="withdrawFunc">
                        <u-loading :show="isSubmitting" mode="circle" color="#FFFFFF"></u-loading>
                        <text v-if="!isSubmitting">确认提现</text>
                    </view>
                </view>
            </view>
        </view>
        
        <u-toast ref="uToast"></u-toast>
    </view>
</template>

<script>
    import {
        apiGetWithdrawInfo,
        apiWithdrawApply
    } from "@/api/user.js"
    
    export default {
        data() {
            return {
                money: '',
                bank: {},
                withdrawInfo: {
                    wallet: '0',
                    min_withdrawal_money: 0,
                    max_withdrawal_money: 0,
                    withdrawal_service_charge: 0
                },
                isSubmitting: false,
                isLoading: true,
                bankList: []
            }
        },
        onLoad() {
            this.initData();
            
            // 添加银行卡选择事件监听
            uni.$on('getBank', (bank) => {
                this.bank = bank;
            });
        },
        onUnload() {
            // 在页面卸载时移除事件监听，防止内存泄漏
            uni.$off('getBank');
        },
        onShow() {
            // 银行卡选择通过事件来处理，不需要从存储获取
            // 如果没有选中的银行，则获取银行列表
            if (!this.bank.id) {
                this.getBankInfo();
            }
        },
        methods: {
            // 初始化数据
            async initData() {
                try {
                    this.isLoading = true;
                    await this.getWithdrawInfoFunc();
                    await this.getBankInfo();
                } catch (error) {
                    console.log('初始化数据失败:', error);
                    this.$refs.uToast.show({
                        title: '数据加载失败，请重试',
                        type: 'error'
                    });
                } finally {
                    this.isLoading = false;
                }
            },
            
            // 获取银行账户信息
            async getBankInfo() {
                try {
                    // 通常银行账户信息应从withdrawInfo.bank_list获取
                    if (this.withdrawInfo && this.withdrawInfo.bank_list && this.withdrawInfo.bank_list.length > 0) {
                        this.bankList = this.withdrawInfo.bank_list;
                        // 如果当前没有选中的银行，则设置默认银行
                        if (!this.bank.id) {
                            this.bank = this.bankList[0] || {};
                        }
                    } else {
                        this.bankList = [];
                        this.bank = {};
                    }
                } catch (error) {
                    console.log('获取银行账户信息出错:', error);
                    this.bankList = [];
                    this.bank = {};
                }
            },
            
            // 获取提现信息
            async getWithdrawInfoFunc() {
                try {
                    const data = await apiGetWithdrawInfo();
					
                        this.withdrawInfo = data
                    
                    // 获取银行账户列表
                    this.bankList = this.withdrawInfo.bank_list || [];
                    
                    // 设置默认银行
                    if (this.bankList.length > 0) {
                        this.bank = this.bankList[0];
                    }
                    
                } catch (error) {
                    console.log('获取提现信息出错:', error);
                    this.withdrawInfo = {
                        wallet: '0',
                        min_withdrawal_money: 0,
                        max_withdrawal_money: 0,
                        withdrawal_service_charge: 0,
                        bank_list: []
                    };
                    throw error;
                }
            },
            
            // 计算手续费
            calculateFee() {
                if (!this.money) return '0.00';
                const rate = this.withdrawInfo.withdrawal_service_charge || 0;
                const fee = (parseFloat(this.money) * rate / 100).toFixed(2);
                return fee;
            },
            
            // 计算实际到账金额
            calculateActual() {
                if (!this.money) return '0.00';
                const total = parseFloat(this.money);
                const fee = parseFloat(this.calculateFee());
                return (total - fee).toFixed(2);
            },
            
            // 设置最大提现金额
            setMaxAmount() {
                if (this.withdrawInfo && this.withdrawInfo.wallet) {
                    this.money = this.withdrawInfo.wallet.toString();
                }
            },
            
            // 页面跳转
            goPage(url) {
                if (url.includes('bank_list')) {
                    // 跳转到银行列表页面
                    uni.navigateTo({
                        url: url
                    });
                } else {
                    uni.navigateTo({
                        url
                    });
                }
            },
            
            // 提现操作
            async withdrawFunc() {
                if (!this.money) {
                    return this.$refs.uToast.show({
                        title: '请输入提现金额',
                        type: 'warning'
                    });
                }
                
                if (!this.bank || !this.bank.id) {
                    return this.$refs.uToast.show({
                        title: '请选择提现账户',
                        type: 'warning'
                    });
                }
                
                // 验证提现金额
                if (this.withdrawInfo.min_withdrawal_money && 
                    parseFloat(this.money) < parseFloat(this.withdrawInfo.min_withdrawal_money)) {
                    return this.$refs.uToast.show({
                        title: `最低提现金额为${this.withdrawInfo.min_withdrawal_money}元`,
                        type: 'warning'
                    });
                }
                
                if (this.withdrawInfo.max_withdrawal_money && 
                    parseFloat(this.money) > parseFloat(this.withdrawInfo.max_withdrawal_money)) {
                    return this.$refs.uToast.show({
                        title: `最高提现金额为${this.withdrawInfo.max_withdrawal_money}元`,
                        type: 'warning'
                    });
                }
                
                if (this.withdrawInfo.wallet && 
                    parseFloat(this.money) > parseFloat(this.withdrawInfo.wallet)) {
                    return this.$refs.uToast.show({
                        title: '提现金额不能大于可提现余额',
                        type: 'warning'
                    });
                }
                
                if (this.isSubmitting) return;
                
                this.isSubmitting = true;
                
                try {
                    const params = {
                        money: this.money,
                        bank_id: this.bank.id
                    }
                    
                    const res = await apiWithdrawApply(params);
                    
                    this.$refs.uToast.show({
                        title: '提现申请已提交',
                        type: 'success',
                        duration: 2000
                    })
                    
                    setTimeout(() => {
                        this.money = '';
                        
                        // 刷新余额信息
                        this.getWithdrawInfoFunc();
                        
                        // 跳转到提现记录页面
                        setTimeout(() => {
                            this.goPage('/bundle/pages/withdraw_record/withdraw_record');
                        }, 1000);
                    }, 1500);
                    
                } catch (error) {
                    console.log(error);
                    this.$refs.uToast.show({
                        title: error.message || '提现申请失败',
                        type: 'error'
                    });
                } finally {
                    this.isSubmitting = false;
                }
            }
        }
    }
</script>

<style lang="scss">
    .withdraw-container {
        min-height: 100vh;
        background-color: #F5F7FA;
        padding-bottom: 40rpx;
    }
    
    /* 加载状态 */
    .loading-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-top: 100rpx;
        
        .loading-text {
            margin-top: 20rpx;
            font-size: 28rpx;
            color: #909399;
        }
    }
    
    /* 余额概览 */
    .account-overview {
        margin: 0 30rpx;
        padding: 30rpx;
        background: linear-gradient(135deg, $-color-primary, lighten($-color-primary, 20%));
        border-radius: 16rpx;
        color: #FFFFFF;
        box-shadow: 0 10rpx 20rpx rgba(64, 158, 255, 0.2);
        margin-top: 20rpx;
        position: relative;
        z-index: 10;
        
        .overview-amount {
            text-align: center;
            
            .overview-label {
                font-size: 28rpx;
                opacity: 0.9;
            }
            
            .overview-value {
                font-size: 56rpx;
                font-weight: bold;
                margin-top: 10rpx;
                display: block;
            }
        }
        
        .overview-details {
            margin-top: 30rpx;
            justify-content: space-around;
            
            .overview-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                
                .item-value {
                    font-size: 32rpx;
                    font-weight: bold;
                }
                
                .item-label {
                    font-size: 24rpx;
                    margin-top: 8rpx;
                    opacity: 0.9;
                }
            }
            
            .overview-divider {
                width: 2rpx;
                height: 50rpx;
                background-color: rgba(255, 255, 255, 0.3);
            }
        }
    }
    
    /* 提现卡片 */
    .withdraw-card {
        margin: 0 30rpx;
        padding: 30rpx;
        background-color: #FFFFFF;
        border-radius: 16rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
        
        .card-title {
            font-size: 32rpx;
            color: #303133;
            font-weight: bold;
        }
    }
    
    /* 银行选择 */
    .bank-selection {
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .management-link {
                display: flex;
                align-items: center;
                
                text {
                    font-size: 28rpx;
                    color: #909399;
                }
            }
        }
        
        .bank-selection-content {
            margin-top: 20rpx;
            
            .empty-bank-tip {
                height: 150rpx;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                border: 2rpx dashed #DCDFE6;
                border-radius: 12rpx;
                
                .empty-tip-text {
                    margin-top: 20rpx;
                    font-size: 28rpx;
                    color: #909399;
                }
                
                &:active {
                    background-color: #F5F7FA;
                }
            }
            
            .selected-bank {
                display: flex;
                align-items: center;
                padding: 30rpx;
                background-color: #F5F7FA;
                border-radius: 12rpx;
                
                .bank-icon {
                    width: 80rpx;
                    height: 80rpx;
                    border-radius: 50%;
                    background-color: #409EFF;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #FFFFFF;
                    font-size: 36rpx;
                    font-weight: bold;
                    margin-right: 24rpx;
                }
                
                .bank-info {
                    flex: 1;
                    
                    .bank-name {
                        font-size: 32rpx;
                        color: #303133;
                        font-weight: 600;
                        display: block;
                    }
                    
                    .bank-account {
                        font-size: 26rpx;
                        color: #909399;
                        margin-top: 8rpx;
                        display: block;
                    }
                }
                
                &:active {
                    opacity: 0.9;
                }
            }
        }
    }
    
    /* 金额输入区域 */
    .amount-input-card {
        .input-container {
            margin-top: 20rpx;
            border-bottom: 2rpx solid #DCDFE6;
            padding-bottom: 20rpx;
            display: flex;
            align-items: center;
            
            .currency-symbol {
                font-size: 44rpx;
                font-weight: bold;
                color: #303133;
                margin-right: 20rpx;
            }
            
            input {
                flex: 1;
                font-size: 48rpx;
                color: #303133;
                height: 80rpx;
            }
        }
        
        .balance-info {
            display: flex;
            align-items: center;
            font-size: 28rpx;
            color: #606266;
        }
        
        .withdraw-all-btn {
            font-size: 28rpx;
            color: $-color-primary;
            padding: 10rpx 20rpx;
            border-radius: 30rpx;
            background-color: rgba(64, 158, 255, 0.1);
        }
    }
    
    /* 费用计算卡片 */
    .fee-card {
        .fee-title {
            font-size: 30rpx;
            font-weight: bold;
            margin-bottom: 20rpx;
        }
        
        .fee-item {
            display: flex;
            justify-content: space-between;
            font-size: 28rpx;
            color: #606266;
            margin-bottom: 16rpx;
            
            &.total {
                font-size: 32rpx;
                font-weight: bold;
                color: #303133;
            }
        }
        
        .fee-divider {
            height: 2rpx;
            background-color: #EBEEF5;
            margin: 20rpx 0;
        }
    }
    
    /* 提示区域 */
    .withdraw-tips {
        .tips-title {
            font-size: 30rpx;
            font-weight: bold;
            margin-bottom: 20rpx;
        }
        
        .tip-item {
            font-size: 28rpx;
            color: #606266;
            display: flex;
            align-items: center;
            margin-bottom: 16rpx;
            
            .tip-bullet {
                width: 12rpx;
                height: 12rpx;
                border-radius: 50%;
                background-color: #DCDFE6;
                margin-right: 16rpx;
            }
        }
    }
    
    /* 按钮样式 */
    .withdraw-btn-container {
        margin: 0 30rpx;
        
        .withdraw-btn {
            height: 94rpx;
            border-radius: 47rpx;
            background: #C0C4CC;
            color: white;
            font-size: 34rpx;
            font-weight: bold;
            box-shadow: 0 8rpx 24rpx rgba(144, 147, 153, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            
            &-active {
                background: linear-gradient(135deg, $-color-primary, lighten($-color-primary, 15%));
                box-shadow: 0 8rpx 24rpx rgba(64, 158, 255, 0.4);
            }
            
            &-disabled {
                opacity: 0.8;
            }
        }
    }
    
    /* 辅助类 */
    .flex {
        display: flex;
    }
    
    .row-between {
        justify-content: space-between;
    }
    
    .m-r-10 {
        margin-right: 10rpx;
    }
    
    .m-t-20 {
        margin-top: 20rpx;
    }
    
    .m-t-30 {
        margin-top: 30rpx;
    }
    
    .m-t-40 {
        margin-top: 40rpx;
    }
    
    .primary-color {
        color: $-color-primary;
    }
    
    .muted {
        color: #909399;
    }
    
    .icon-margin {
        margin-right: 12rpx;
    }
</style>